package com.xyg.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.xyg.exception.NotLoggedInException;
import com.xyg.pojo.Result;
import com.xyg.pojo.Review;
import com.xyg.service.ReviewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping( "/api/reviews" )
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    /**
     * 获取指定产品的所有评论。
     */
    @GetMapping( "/product/{productId}" )
    public Result< List< Review > > getReviewsByProductId ( @PathVariable String productId ) {
        if ( productId == null || productId.isEmpty() ) {
            return Result.failure( 400, "商品ID不能为空" );
        }
        List< Review > reviews = reviewService.findReviewsByProductId( productId );
        if ( reviews.isEmpty() ) {
            return Result.failure( 404, "未找到该商品的评论" );
        }
        return Result.success( "查询当前商品评论成功", reviews );
    }

    /**
     * 添加新评论。
     */
    @PostMapping
    public Result< Review > createReview ( @RequestBody Review review ) throws NotLoggedInException {
        if ( review == null || review.getComment() == null || review.getComment().isEmpty() ) {
            return Result.failure( 400, "评论内容不能为空" );
        }

        // 验证登录状态
        if ( !StpUtil.isLogin() ) {
            throw new NotLoggedInException( "用户未登录，请先登录", HttpStatus.UNAUTHORIZED );
        }

        Review addedReview = reviewService.save( review );
        return Result.success( "添加评论成功", addedReview );
    }

}